package com.donger.upms.biz.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.donger.common.log.annotation.Log;
import com.donger.common.core.exception.BizException;
import com.donger.common.core.utils.Res;
import com.donger.common.core.utils.Result;
import com.donger.common.security.service.UserDetail;
import com.donger.common.security.utils.SecurityUtil;
import com.donger.upms.api.entity.SysPermission;
import com.donger.upms.api.service.ISysPermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单管理 前端控制器
 * </p>
 *
 */
@AllArgsConstructor
@RestController
@RequestMapping("/sys/permission")
@Slf4j
public class SysPermissionController{

    private static final String MODULE_NAME = "系统权限管理";

    private final ISysPermissionService sysPermissionService;



    /**
     * 所有权限列表
     */
    @GetMapping("/tree")
    public Result<List<SysPermission>> list() {
        // 获取当前用户的角色
        UserDetail user = SecurityUtil.getUser();
        List<SysPermission> permissionList = sysPermissionService.getUserMenuList(user.getUserId());
        return Res.ok(permissionList);
    }


    /**
     * 菜单信息
     */
    @GetMapping("/info/{menuId}")
    public Result<SysPermission> info(@PathVariable("menuId") Long menuId) {
        return Res.ok(sysPermissionService.getById(menuId));
    }

    /**
     * 保存
     */
    @Log(value = "保存菜单", moduleName = MODULE_NAME)
    @PostMapping("/save")
    @PreAuthorize("@pms.hasPermission('sys:permission:add')")
    public Result<Boolean> save(@RequestBody @Valid SysPermission menu) {
        if(menu.getParentId() == null){
            menu.setParentId(0L);
        }
        return Res.ok(sysPermissionService.save(menu));
    }

    /**
     * 修改
     */
    @Log(value = "修改菜单", moduleName = MODULE_NAME)
    @PostMapping("/update")
    @PreAuthorize("@pms.hasPermission('sys:permission:update')")
    public Result<Boolean> update(@RequestBody SysPermission menu) {
        //数据校验
        verifyForm(menu);
        return Res.ok(sysPermissionService.updateById(menu));
    }

    /**
     * 删除
     */
    @Log(value = "删除菜单", moduleName = MODULE_NAME)
    @DeleteMapping("/delete/{menuId}")
    @ApiOperation("根据权限ID删除权限,具备权限:sys:permission:delete")
    @PreAuthorize("@pms.hasPermission('sys:permission:delete')")
    public Result<Boolean> delete(@PathVariable("menuId") Long menuId) {
        //判断是否有子菜单或按钮
        List<SysPermission> menuList = sysPermissionService.queryListParentId(menuId);
        if (menuList.size() > 0) {
            return Res.error("请先删除子菜单或按钮");
        }
        sysPermissionService.removeById(menuId);
        return Res.ok();
    }


    /**
     * 查询改角色所拥有的 菜单权限id
     *
     * @param roleId
     * @return
     */
    @GetMapping("/tree/{roleId}")
    @ApiOperation(value = "获取某角色ID的权限ID列表")
    public Result selectByRoleId(@PathVariable("roleId") @ApiParam("角色ID") Long roleId) {
        List<Long> menuIds = sysPermissionService.findMenuByRoleId(roleId).stream().map(SysPermission::getId).collect(Collectors.toList());
        return Res.ok(menuIds);
    }

    /**
     * 验证参数是否正确
     */
    private void verifyForm(SysPermission menu) {
        if (StrUtil.isBlank(menu.getTitle())) {
            throw new BizException("菜单名称不能为空");
        }

        if (menu.getParentId() == null) {
            throw new BizException("上级菜单不能为空");
        }

    }
}

